﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BusinessLogicLayer;

namespace PresentationLayer
{
    public partial class frmCurrency : Form
    {
        #region Properties
        private frmMain MdiForm { get; set; }
        private enumState State { get; set; }
        enum enumState
        {
            View,
            New,
            Edit
        }
        #endregion

        #region Constructors
        public frmCurrency(frmMain pMdiForm)
        {
            InitializeComponent();
            this.MdiForm = pMdiForm;
        }
        #endregion

        #region Events
        private void frmCurrency_Load(object sender, EventArgs e)
        {
            this.MdiForm.Event_OnTranslationChanged += new frmMain.OnTranslationChangedHandler(Translate);
            Translate();
            FillComboBoxCurrencyName();
            FillListViewCurrency();
            SetButtonsToState(enumState.View);
            SetTextBoxToState(enumState.View);
        }

        private void txtCurrencyValue_KeyPress(object sender, KeyPressEventArgs e)
        {
            String DotChar = CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
            if ((e.KeyChar <= 57 && e.KeyChar >= 48) || (e.KeyChar == 8 || e.KeyChar == Convert.ToChar(DotChar)))
            {
            }
            else
            {
                e.Handled = true;
            }
        }

        private void lsvCurrency_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillListViewValue();
        }

        private void lsvValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillFieldsWithCurrencyDetails();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            SetButtonsToState(enumState.View);
            SetTextBoxToState(enumState.View);
            FillFieldsWithCurrencyDetails();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            SetButtonsToState(enumState.New);
            SetTextBoxToState(enumState.New);
            cboCurrencyName.Select();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            SetButtonsToState(enumState.Edit);
            SetTextBoxToState(enumState.Edit);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Delete();
        }

        private void cboCurrencyName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboCurrencyName.SelectedItem != null)
            {
                clsCurrency Currency = (clsCurrency)cboCurrencyName.SelectedItem;
                txtCurrencyAbbrevation.Text = Currency.CurrencyAbbrevation;
            }
        }

        private void cboCurrencyName_TextChanged(object sender, EventArgs e)
        {
            if (txtCurrencyAbbrevation.Text != "")
            {
                txtCurrencyAbbrevation.Text = "";
            }
        }
        #endregion

        #region Public Methods
        #endregion

        #region Private Methods
        /// <summary>
        /// Fills the languages ComboBox with all languages except the system language English.
        /// </summary>
        private void FillComboBoxCurrencyName()
        {
            if (cboCurrencyName.Items.Count > 0)
            {
                cboCurrencyName.Items.Clear();
            }

            ArrayList CurrencyNames = this.MdiForm.DataAccess.GetAllLatestCurrencies();
            foreach (clsCurrency CurrencyName in CurrencyNames)
            {
                cboCurrencyName.Items.Add(CurrencyName);
            }
        }

        /// <summary>
        /// Deletes a currency.
        /// </summary>
        private void Delete()
        {
            clsCurrency Currency = (clsCurrency)lsvValue.SelectedItems[0].Tag;
            switch (MessageBox.Show("Do you really want to delete '" + Currency.CurrencyName + " = " + Currency.CurrencyValue + "'?", "Delete", MessageBoxButtons.YesNo))
            {
                case DialogResult.Yes:
                    if (this.MdiForm.DataAccess.DeleteCurrency(GetCurrencyID()))
                    {
                        FillListViewCurrency();
                        SetButtonsToState(enumState.View);
                        SetTextBoxToState(enumState.View);
                    }
                    break;
                default:
                    break;
            }

        }

        /// <summary>
        /// Saves the currency.
        /// </summary>
        private void Save()
        {
            if (SaveCurrency())
            {
                FillListViewCurrency();
                SetButtonsToState(enumState.View);
                SetTextBoxToState(enumState.View);
            }
        }

        /// <summary>
        /// Saves the currency depending on the actual state.
        /// </summary>
        /// <returns>State of success.</returns>
        private Boolean SaveCurrency()
        {
            Boolean Success = false;
            if (CheckIfTextBoxesEmpty() == false)
            {
                switch (this.State)
                {
                    case enumState.New:
                        Success = this.MdiForm.DataAccess.InsertCurrency(cboCurrencyName.Text, txtCurrencyAbbrevation.Text, Convert.ToDouble(txtCurrencyValue.Text), dtpEffectiveFrom.Value);
                        break;
                    case enumState.Edit:
                        Success = this.MdiForm.DataAccess.ChangeCurrency(GetCurrencyID(), cboCurrencyName.Text, txtCurrencyAbbrevation.Text, Convert.ToDouble(txtCurrencyValue.Text), dtpEffectiveFrom.Value);
                        break;
                }
            }
            if (Success == false)
            {
                MessageBox.Show("Error saving currency.");
            }
            return Success;
        }

        /// <summary>
        /// Gets the actually selected currency ID.
        /// </summary>
        /// <returns>The ID of the currency.</returns>
        private Int32 GetCurrencyID()
        {
            if (lsvValue.SelectedItems.Count > 0)
            {
                clsCurrency Currency = (clsCurrency)lsvValue.SelectedItems[0].Tag;
                return Currency.ID;
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// Checks the emptyness of the TextBoxes.
        /// </summary>
        /// <returns>True if TextBoxes are empty.</returns>
        private Boolean CheckIfTextBoxesEmpty()
        {
            if (cboCurrencyName.Text == "")
            {
                return true;
            }

            if (txtCurrencyAbbrevation.Text == "")
            {
                return true;
            }

            if (txtCurrencyValue.Text == "" || txtCurrencyValue.Text == "0")
            {
                return true;
            }
            else
            {
                Double OutVar = 0;
                if (Double.TryParse(txtCurrencyValue.Text, out OutVar) == false)
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Applies the state to the buttons.
        /// </summary>
        /// <param name="pState">The state.</param>
        private void SetButtonsToState(enumState pState)
        {
            this.State = pState;
            switch (this.State)
            {
                case enumState.View:
                    btnCancel.Enabled = false;
                    btnSave.Enabled = false;
                    if (lsvValue.SelectedItems.Count > 0 && lsvValue.SelectedItems[0].Index > -1)
                    {
                        btnEdit.Enabled = true;
                        btnDelete.Enabled = true;
                    }
                    else
                    {
                        btnEdit.Enabled = false;
                        btnDelete.Enabled = false;
                    }
                    break;
                case enumState.New:
                    btnCancel.Enabled = true;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = true;
                    break;
                case enumState.Edit:
                    btnCancel.Enabled = true;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = true;
                    break;
            }
        }

        /// <summary>
        /// Applies the state to the TextBoxes.
        /// </summary>
        /// <param name="pState">The state.</param>
        private void SetTextBoxToState(enumState pState)
        {
            this.State = pState;
            switch (this.State)
            {
                case enumState.View:
                    lsvCurrency.Enabled = true;
                    txtCurrencyAbbrevation.Enabled = false;
                    lsvValue.Enabled = true;
                    cboCurrencyName.Enabled = false;
                    txtCurrencyValue.Enabled = false;
                    dtpEffectiveFrom.Enabled = false;
                    break;
                case enumState.New:
                    lsvCurrency.Enabled = false;
                    txtCurrencyAbbrevation.Enabled = true;
                    lsvValue.Enabled = false;
                    cboCurrencyName.Enabled = true;
                    txtCurrencyValue.Enabled = true;
                    dtpEffectiveFrom.Enabled = true;
                    cboCurrencyName.Text = "";
                    txtCurrencyAbbrevation.Text = "";
                    txtCurrencyValue.Text = "";
                    dtpEffectiveFrom.Value = DateTime.Now;
                    break;
                case enumState.Edit:
                    lsvCurrency.Enabled = false;
                    txtCurrencyAbbrevation.Enabled = true;
                    lsvValue.Enabled = false;
                    cboCurrencyName.Enabled = true;
                    txtCurrencyValue.Enabled = true;
                    dtpEffectiveFrom.Enabled = true;
                    break;
            }
        }

        /// <summary>
        /// Fills the ListView with currencies.
        /// </summary>
        /// <param name="pSearchArgument"></param>
        private void FillListViewCurrency()
        {
            //Delete all ListView items if available.
            if (lsvCurrency.Items.Count > 0)
            {
                lsvCurrency.Items.Clear();
            }
            //Get all currencies.
            ArrayList Currencies = this.MdiForm.DataAccess.GetAllCurrencies();
            for (Int32 i = 0; i < Currencies.Count; i++)
            {
                //Get currency.
                clsCurrency CurrencyRow = (clsCurrency)Currencies[i];
                //Create item for ListView.
                ListViewItem Item = new ListViewItem(CurrencyRow.CurrencyName);
                Item.Tag = CurrencyRow;
                //Add item to ListView.
                lsvCurrency.Items.Add(Item);
            }
            //Resize columns adapted to contents.
            lsvCurrency.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            //Select the first item if possible.
            if (lsvCurrency.Items.Count > 0)
            {
                lsvCurrency.Items[0].Selected = true;
            }
            else
            {
                FillListViewValue();
            }
        }

        /// <summary>
        /// Fills the ListView with values.
        /// </summary>
        /// <param name="pSearchArgument"></param>
        private void FillListViewValue()
        {
            //Delete all ListView items if available.
            if (lsvValue.Items.Count > 0)
            {
                lsvValue.Items.Clear();
            }

            //Fill values ListView with the currency values of the currency selected in the currency ListView.
            if (lsvCurrency.SelectedItems.Count > 0)
            {
                clsCurrency Currency = (clsCurrency)lsvCurrency.SelectedItems[0].Tag;
                foreach (clsCurrency CurrencyValue in Currency.GetCurrencyValues())
                {
                    //Create item for ListView.
                    ListViewItem Item = new ListViewItem(CurrencyValue.EffectiveFrom.ToString("dd.MM.yyyy"));
                    Item.SubItems.Add(CurrencyValue.CurrencyValue.ToString());
                    Item.Tag = CurrencyValue;
                    //Add item to ListView.
                    lsvValue.Items.Add(Item);
                }
            }

            //Resize columns adapted to contents.
            lsvValue.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

            //Select the first item if possible.
            if (lsvValue.Items.Count > 0)
            {
                lsvValue.Items[0].Selected = true;
            }
            else
            {
                FillFieldsWithCurrencyDetails();
            }
        }

        /// <summary>
        /// Translates every visible element.
        /// </summary>
        private void Translate()
        {
            this.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, "Text", this.Text, 0);
            grpCurrency.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, grpCurrency.Name, grpCurrency.Text, 0);
            grpValue.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, grpValue.Name, grpValue.Text, 0);
            grpDetails.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, grpDetails.Name, grpDetails.Text, 0);
            lblCurrencyName.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblCurrencyName.Name, lblCurrencyName.Text, 0);
            lblCurrencyAbbrevation.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblCurrencyAbbrevation.Name, lblCurrencyAbbrevation.Text, 0);
            lblCurrencyValue.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblCurrencyValue.Name, lblCurrencyValue.Text, 0);
            lblEffectiveFrom.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblEffectiveFrom.Name, lblEffectiveFrom.Text, 0);
            lblDateCreated.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblDateCreated.Name, lblDateCreated.Text, 0);
            lblDateChanged.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblDateChanged.Name, lblDateChanged.Text, 0);
            grpOptions.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, grpOptions.Name, grpOptions.Text, 0);
            btnCancel.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, btnCancel.Name, btnCancel.Text, 0);
            btnNew.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, btnNew.Name, btnNew.Text, 0);
            btnEdit.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, btnEdit.Name, btnEdit.Text, 0);
            btnSave.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, btnSave.Name, btnSave.Text, 0);
            btnDelete.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, btnDelete.Name, btnDelete.Text, 0);
            FillByFields();
            InitializeListViewCurrency();
            InitializeListViewValue();
        }

        /// <summary>
        /// Initializes the currency ListView.
        /// </summary>
        private void InitializeListViewCurrency()
        {
            if (lsvCurrency.Columns.Count > 0)
            {
                lsvCurrency.Columns.Clear();
            }
            lsvCurrency.Columns.Add(this.MdiForm.DataAccess.GetTranslation(this.Name, lsvCurrency.Name + "_Currency", "Currency", 0));
            lsvCurrency.View = View.Details;
            lsvCurrency.FullRowSelect = true;
            lsvCurrency.HideSelection = false;
            lsvCurrency.MultiSelect = false;
        }

        /// <summary>
        /// Initializes the value ListView.
        /// </summary>
        private void InitializeListViewValue()
        {
            if (lsvValue.Columns.Count > 0)
            {
                lsvValue.Columns.Clear();
            }
            lsvValue.Columns.Add(this.MdiForm.DataAccess.GetTranslation(this.Name, lsvValue.Name + "_Effective from", "Effective from", 0));
            lsvValue.Columns.Add(this.MdiForm.DataAccess.GetTranslation(this.Name, lsvValue.Name + "_Currency value", "Currency value", 0));
            lsvValue.View = View.Details;
            lsvValue.FullRowSelect = true;
            lsvValue.HideSelection = false;
            lsvValue.MultiSelect = false;
        }

        /// <summary>
        /// Only fills the "by"-Fields.
        /// </summary>
        private void FillByFields()
        {
            if (lsvCurrency.SelectedItems.Count > 0 && lsvValue.SelectedItems.Count > 0)
            {
                lblCreatedBy.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblCreatedBy.Name, "by", 0);
                lblChangedBy.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblChangedBy.Name, "by", 0);
            }
            else
            {
                lblCreatedBy.Text = "";
                lblChangedBy.Text = "";
            }
        }

        /// <summary>
        /// Fill the fields with the selection details.
        /// </summary>
        private void FillFieldsWithCurrencyDetails()
        {
            if (lsvCurrency.SelectedItems.Count > 0 && lsvValue.SelectedItems.Count > 0)
            {
                clsCurrency CurrencyRow = (clsCurrency)lsvValue.SelectedItems[0].Tag;

                cboCurrencyName.Text = CurrencyRow.CurrencyName;
                if (txtCurrencyAbbrevation.Text != CurrencyRow.CurrencyAbbrevation)
                {
                    txtCurrencyAbbrevation.Text = CurrencyRow.CurrencyAbbrevation;
                }
                txtCurrencyValue.Text = CurrencyRow.CurrencyValue.ToString();
                dtpEffectiveFrom.Value = CurrencyRow.EffectiveFrom;
                lblDateCreatedVal.Text = CurrencyRow.DateCreated.ToString();
                lblDateChangedVal.Text = CurrencyRow.DateChanged.ToString();
                lblCreatedBy.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblCreatedBy.Name, "by", 0);
                lblChangedBy.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblChangedBy.Name, "by", 0);
                lblUserCreatedVal.Text = CurrencyRow.UserCreated;
                lblUserChangedVal.Text = CurrencyRow.UserChanged;
            }
            else
            {
                cboCurrencyName.Text = "";
                txtCurrencyAbbrevation.Text = "";
                txtCurrencyValue.Text = "";
                dtpEffectiveFrom.Value = DateTime.Now;
                lblDateCreatedVal.Text = "";
                lblDateChangedVal.Text = "";
                lblCreatedBy.Text = "";
                lblChangedBy.Text = "";
                lblUserCreatedVal.Text = "";
                lblUserChangedVal.Text = "";
            }

            SetButtonsToState(enumState.View);
            SetTextBoxToState(enumState.View);
        }
        #endregion
    }
}
